package com.jdew.thkj.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.baichuan.trade.biz.alipay.AliPayResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.google.gson.JsonObject;
import com.jdew.thkj.PayResult;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.JDBean;
import com.jdew.thkj.bean.NewCodeBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;

import java.util.HashMap;
import java.util.Map;

import javax.xml.transform.Result;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CustomInvitationCodeActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.code)
    TextView code;
    @Bind(R.id.setting)
    ImageView setting;
    private String orderNo;
    private static final int SDK_PAY_FLAG = 1;
    private boolean canBack=false;

    @Override
    public int bindLayout() {
        return R.layout.activity_custom_invitator_code;
    }

    @Override
    public void initView(View view) {
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        back.setOnClickListener(this);
        setting.setOnClickListener(this);
        title.setText("自定义邀请码");
        code.setText(sp.getString("SpareOne", ""));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.setting: {
                String message = "1.自定义邀请码设置是付费功能，需要付款99元才能使用该功能。\n" + "2.你可以自定义纯文汉字或者纯数字的邀请码，方便自己推广，注意不要设置连号超过三位的邀请码。\n" + "3.付款成功后即视为接受接受淘乐惠提供的该服务，不接受退款处理";
                commomDialog(message);
            }
            break;
        }
    }

    public void commomDialog(String Message) {
        new CommonDialog.Builder(this, Message)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity3()
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        RequestData();
                    }
                })
                .setNegativeButton("取消", null).show3();
    }

    public void commomDialog2() {
        canBack=false;
        new CommonDialog.Builder(this, true, 0)
                .setTitle2("自定义邀请码")
                .setCanceledOnTouchOutside(false)
                .setMessageGravity2()
                .setPositiveButton2("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CustomNumber();
                    }
                }).show2();
    }

    public void commomDialog3(String Message) {
        new CommonDialog.Builder(this, Message)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity()
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                })
                .setNegativeButton("取消", null).show4();
    }
    public void RequestData() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("Id", sp.getString("userId", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).setAliPlayCustomNumber(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Id" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                orderNo = obj.getString("data");
                final String orderInfo = orderNo;   // 订单信息
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(CustomInvitationCodeActivity.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.getInstance(CustomInvitationCodeActivity.this).showMessage("支付成功");
                        commomDialog2();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.getInstance(CustomInvitationCodeActivity.this).showMessage("支付取消");
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    public void CustomNumber() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("UserCode", sp.getString("newUserCode", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).CustomNumber(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserCode" + sp.getString("newUserCode", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    canBack=true;
                    setCustomNumber();
                } else {
                    commomDialog2();
                }
                ToastUtils.getInstance(CustomInvitationCodeActivity.this).showMessage(obj.getString("message"));
            }
        });
    }

    public void setCustomNumber() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("UserCode", sp.getString("newUserCode", ""));
        map.put("UserId", sp.getString("userId", ""));
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).setCustomNumber(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserCode" + sp.getString("newUserCode", "") + "UserId" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<NewCodeBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(NewCodeBean bean) {
                if (bean.getCode().equals("0")) {
                     editor.putString("newUserCode","");
                     editor.apply();
                } else {
                    commomDialog2();
                }
                commomDialog3(bean.getMessage());
            }
        });
    }
}
